<?php

/**
 * Referral form.
 *
 * @package    docplus.co.za
 * @subpackage form
 * @author     Fox Matuku
 * @version    SVN: $Id: sfDoctrineFormTemplate.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class ReferralForm extends BaseReferralForm
{
    protected $cardinals = array('1st', '2nd', '3rd', '4th', '5th');

    public function configure()
    {
        unset(
            $this['created_at'], $this['updated_at']
        );

        $this->widgetSchema['from_name']->setLabel('Your name');
        $this->widgetSchema['from_email']->setLabel('Your email');
        
        $this->validatorSchema['from_name'] = new sfValidatorString(array("required" => true), array("required" => '*Your name* is required.'));
        $this->validatorSchema['from_email'] = new sfValidatorEmail(array("required" => true), array("invalid" => '*Your email* is invalid.', "required" => '*Your email* is required.'));
        $this->validatorSchema['message'] = new sfValidatorString(array("required" => true), array("required" => '*Your message* is required.'));

        if (!$friends = $this->getOption('friends'))
        {
            throw new InvalidArgumentException('You must provide number of friends you would thank to refer to DocPlus.');
        }

        // loop through creating multiple friends on the popup
        for ($i = 0; $i < $friends; $i++)
        {
            $cardinal = $this->cardinals[$i];
            $form = new ReferralFriendForm(array(), array('cardinal' => $cardinal));
            $this->embedForm($i, $form);
        }
    }

    public function Save($con = null)
    {
        // unset the embedded forms values
        $values = array();
        $friends = $this->getOption('friends');
        for ($i = $friends - 1; $i >= 0; $i--)
        {
            $values[] = $this->values[$i];
            unset($this->values[$i]);
        }
        
        // save this referral form
        $referral = parent::save();

        // save all embedded forms
        for ($i = $friends - 1; $i >= 0; $i--)
        {
            $referralFriend = new ReferralFriend();
            $referralFriend->setReferralId($referral->getId());
            $referralFriend->setName($values[$i]['name']);
            $referralFriend->setEmail($values[$i]['email']);
            $referralFriend->save();
        }
    }

    protected function doSave($con = null)
    {
        if (null === $con)
        {
            $con = $this->getConnection();
        }

        $this->updateObject();
        $this->getObject()->save($con);
    }

}
